from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import redirect, render,HttpResponse

from app01.models import UserInfo


# Create your views here.

def index(request):
    return HttpResponse('欢迎使用！')

def user_list(request):
    roles = [
        {"role":"管理员","name":'张三'},
        {"role":"用户1","name":'李四'}
        ]

    # 1.去app01目录下的templates下去寻找user_list.html(根据app的注册顺序INSTALLED_APPS，逐一去他们的templates目录下去找)
    # 如果需要去根目录下的templates下找，需要在settings.py文件中的DIRS进行配置
    return render(request,"user_list.html",{"params1":roles})

def news(req):
    # 网络请求获取数据
    # 向地址发送请求：https://www.chinaunicom.cn/api/article/NewsByIndex/2/2023/10/news
    # 第三方模块： requests
    import requests
    r = requests.get('https://www.chinaunicom.cn/api/article/NewsByIndex/4/2023/10/news', headers={"User-Agent": "text/plain;charset=UTF-8"})
    data_list = r.json()

    return render(req,'news.html',{"news_list":data_list})

def redirectBaidu(request):
    return redirect("https://www.baidu.com")

def login(request):
    if request.method == 'GET':
        return render(request,'login.html')

    # 获取用户数据
    print(request.POST)

    username = request.POST.get('user')
    password = request.POST.get('pwd')

    if(username == '1' and password == '1'):
        # return HttpResponse('登录成功')
        # return redirect('https://www.baidu.com')
        return HttpResponseRedirect('/news/')
    
    return render(request,'login.html',{"error_msg":"用户名密码错误"})

# 注册
def register(request):
    if(request.method == 'GET'):
        return render(request,"register.html")
    print(request.POST)
    username = request.POST.get('user')
    pwd = request.POST.get('pwd')
    age = request.POST.get('age')

    from app01.models import UserInfo
    UserInfo.objects.create(name=username,password=pwd,age=age)
    return redirect('/manage/user/')

def manageUser(req):
    userList = UserInfo.objects.all()
    return render(req,'manage_user.html',{"userList":userList})    
    

def delUser(req):
    uid = req.GET.get("uid")
    print('uid',uid)
    UserInfo.objects.filter(id=uid).delete()
    # return HttpResponse('删除成功')
    return redirect('/manage/user/')

# 修改用户信息
def updateUser(request):
    if(request.method == 'GET'):
        uid = request.GET.get('uid')
        userData = UserInfo.objects.filter(id=uid).first()
        return render(request,"register.html",{"userData":userData})
    uid = request.POST.get('id')
    username = request.POST.get('user')
    pwd = request.POST.get('pwd')
    age = request.POST.get('age')

    UserInfo.objects.filter(id=uid).update(name=username,password=pwd,age=age)
    return redirect('/manage/user/')